﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YAPACS.BusinessObjects.Exams;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Register;

public class SetTop(IRepository<ExamQueuing, Guid> examQueuingRepository, IAsyncQueryableExecuter queryableExecuter, IExamEventService examEventService) : WorkflowBase, ISetTop, ITransientDependency
{
    private readonly IRepository<ExamQueuing, Guid> _examQueuingRepository = examQueuingRepository;
    private readonly IAsyncQueryableExecuter _queryableExecuter = queryableExecuter;
    private readonly IExamEventService _examEventService = examEventService;

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        const string key = "Exam";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Exam exam)
        {
            var startTime = Clock.Now.Date;
            var endTime = Clock.Now.Date.AddDays(1);

            var query = await _examQueuingRepository.GetQueryableAsync();
            query = query.Where(e => e.StartTime >= startTime && e.EndTime < endTime);
            query = query.Where(e => e.Status == ExamQueuingStatus.Wait);

            if (exam.ExamDevice != null)
            {
                query = query.Where(e => e.Device == exam.ExamDevice);
            }
            else
            {
                query = query.Where(e => e.ExamCategory == exam.ExamCategory);
            }

            var examQueuing = await _queryableExecuter.FirstOrDefaultAsync(query.OrderBy(e => e.Order));
            if (examQueuing != null)
            {
                if (examQueuing.Oid != exam.ExamQueuing.Oid)
                {
                    exam.ExamQueuing.Order = examQueuing.Order - ExamQueuing.ORDER_SPACING;
                    await _examEventService.AddExamEventAsync(exam, "置顶患者");
                }
                else
                {
                    exam.ExamQueuing.Order = 0;
                }
            }

            return new WorkflowOutput
            {
                Success = true
            };
        }
        return new WorkflowOutput() { Success = false, Error = "未找到检查对象" };
    }
}
